package com.example.choupaiapp.main.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videoplayer.player.VideoView;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.activity.home.OtherInfoActivity;
import com.example.choupaiapp.main.bean.VideoListBean;
import com.example.choupaiapp.main.callback.VideoClickListener;
import com.example.choupaiapp.main.util.video.PreloadManager;
import com.example.choupaiapp.main.util.video.VideoDetailHashMap;
import com.orhanobut.logger.Logger;
import com.shuyu.textutillib.RichTextView;
import com.shuyu.textutillib.listener.SpanAtUserCallBack;
import com.shuyu.textutillib.model.UserModel;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class VerticalViewPagerAdapter extends PagerAdapter {

    /**
     * View缓存池，从ViewPager中移除的item将会存到这里面，用来复用
     */
    private List<View> mViewPool = new ArrayList<>();

    /**
     * 数据源
     */
    private List<VideoListBean> mVideoBeans;

    private VideoClickListener videoCommentClickListener;

    public VerticalViewPagerAdapter(List<VideoListBean> videoBeans, VideoClickListener videoCommentClickListener) {
        this.mVideoBeans = videoBeans;
        this.videoCommentClickListener = videoCommentClickListener;
    }

    public static void startActivity(Class<?> cls, @Nullable Bundle bundle) {
        Intent intent = new Intent(ContextUtil.getContext(), cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        ContextUtil.getContext().startActivity(intent);
    }


    @Override
    public int getCount() {
        return mVideoBeans == null ? 0 : mVideoBeans.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        Context context = container.getContext();
        View view = null;
//        if (mViewPool.size() > 0) {//取第一个进行复用
//            view = mViewPool.get(0);
//            mViewPool.remove(0);
//        }

        VideoListBean item = mVideoBeans.get(position);
        ViewHolder viewHolder;
        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.item_video_detail, container, false);
            viewHolder = new ViewHolder(view, item.getContentId(), position);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }


        //开始预加载
        Logger.e(item.getVideoDownloadUrl()+"+++"+position);
        PreloadManager.getInstance(context).addPreloadTask(item.getVideoDownloadUrl(), position);
        Glide.with(context)
                .load(item.getCoverImgUrl())
                .placeholder(android.R.color.black)
                .into(viewHolder.controller.getThumb());

        viewHolder.custom_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoCommentClickListener != null) {
                    if (Utils.isDoubleClick()) {
                        return;
                    }
                    videoCommentClickListener.onBack();
                }
            }
        });

        //评论
        viewHolder.comment_tv.setText(item.getComment_num() + "");
        viewHolder.comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoCommentClickListener != null) {
                    if (Utils.isDoubleClick()) {
                        return;
                    }
                    videoCommentClickListener.onCommentClick(position);
                }
            }
        });

        //点赞
        viewHolder.praise_tv.setText(item.getPraise_num() + "");
        if (item.getIsLike() == 1) {
            viewHolder.praise_iv.setImageResource(R.mipmap.icon_praise_select);
        } else {
            viewHolder.praise_iv.setImageResource(R.mipmap.item_praise);
        }
        viewHolder.praise_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoCommentClickListener != null) {
                    if (Utils.isDoubleClick()) {
                        return;
                    }
                    videoCommentClickListener.onPraiseClick(position);
                }
            }
        });

        //分享
        viewHolder.share_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoCommentClickListener != null) {
                    if (Utils.isDoubleClick()) {
                        return;
                    }
                    videoCommentClickListener.onShareClick(position);
                }
            }
        });

        //头像 昵称
        if (item.getAnonymity() == 1) {
            viewHolder.name.setText("匿名用户");
            Glide.with(context)
                    .load("")
                    .dontAnimate()
                    .placeholder(R.mipmap.head_anonymous_orange)
                    .into(viewHolder.head_photo);
        } else {
            viewHolder.name.setText(item.getNickName());
            Glide.with(context)
                    .load(item.getHeadPhoto())
                    .dontAnimate()
                    .placeholder(R.mipmap.head_anonymous_orange)
                    .into(viewHolder.head_photo);
        }
        viewHolder.head_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoCommentClickListener != null) {
                    if (Utils.isDoubleClick()) {
                        return;
                    }
                    videoCommentClickListener.onHeadClick(position);
                }
            }
        });

        List<UserModel> list = new ArrayList<>();
        for(int i=0;i<item.getList().size();i++){
            UserModel userModel = new UserModel();
            userModel.setUser_name(item.getList().get(i).getNickname());
            userModel.setUser_id(item.getList().get(i).getUserId()+"");
            list.add(userModel);
        }

//        viewHolder.desc.setText(item.getTitle());
        //所有配置完成后才设置text
        viewHolder.desc.setRichTextUser(item.getTitle(), list);
        viewHolder.desc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoCommentClickListener != null) {
                    if (Utils.isDoubleClick()) {
                        return;
                    }
                    videoCommentClickListener.toDetail(position);
                }
            }
        });

        viewHolder.time.setText(item.getTime().split(" ")[0].replace("-", "/"));

        viewHolder.mPosition = position;
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        View itemView = (View) object;
        container.removeView(itemView);
        VideoListBean item = mVideoBeans.get(position);
        //取消预加载
        PreloadManager.getInstance(container.getContext()).removePreloadTask(item.getVideoDownloadUrl());
//        //保存起来用来复用
//        mViewPool.add(itemView);
    }

    private static SpanAtUserCallBack spanAtUserCallBack = new SpanAtUserCallBack() {
        @Override
        public void onClick(View view, UserModel userModel1) {
            Bundle bundle = new Bundle();
            bundle.putString("userId", userModel1.getUser_id());
            bundle.putString("userName", userModel1.getUser_name());
            startActivity(OtherInfoActivity.class, bundle);
            if (view instanceof TextView) {
                ((TextView) view).setHighlightColor(Color.TRANSPARENT);
            }
        }
    };

    /**
     * 借鉴ListView item复用方法
     */
    public static class ViewHolder {

        public VideoView mVideoView;
        public int mPosition;
        public StandardVideoController controller;
        private FrameLayout container;
        public RichTextView desc;
        public TextView name;
        public TextView time;
        public CircleImageView head_photo;
        public LinearLayout comment;
        public TextView comment_tv;
        public LinearLayout praise_ll;
        public ImageView praise_iv;
        public TextView praise_tv;
        public LinearLayout share_ll;
        public ImageView custom_back;

        ViewHolder(View itemView, int id, int mPosition) {
            this.mPosition = mPosition;
//            mVideoView = itemView.findViewById(R.id.video_view);
            itemView.setTag(this);
            mVideoView = VideoDetailHashMap.getIntance().get(id);
            container = itemView.findViewById(R.id.container);
            container.removeAllViews();

            controller = new StandardVideoController(itemView.getContext());
            custom_back = controller.findViewById(R.id.custom_back);
            desc = controller.findViewById(R.id.desc);

            desc.setAtColor(Color.parseColor(itemView.getContext().getString(R.string.remind_color)));
            desc.setLinkColor(Color.BLUE);
            desc.setSpanAtUserCallBackListener(spanAtUserCallBack);

            name = controller.findViewById(R.id.name);
            time = controller.findViewById(R.id.time);
            head_photo = controller.findViewById(R.id.head_photo);
            comment = controller.findViewById(R.id.comment_ll);
            comment_tv = controller.findViewById(R.id.comment_tv);
            praise_ll = controller.findViewById(R.id.praise_ll);
            praise_iv = controller.findViewById(R.id.praise_iv);
            praise_tv = controller.findViewById(R.id.praise_tv);
            share_ll = controller.findViewById(R.id.share_ll);

            if(mVideoView==null){
                mVideoView = new VideoView(ContextUtil.getContext());
            }

            removePlayerFormParent(mVideoView);
            mVideoView.setLooping(true);
//            mVideoView.setMute(false);
            mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_DEFAULT);

            mVideoView.setVideoController(controller);
            controller.setPlayState(mVideoView.getCurrentPlayState());
            controller.setPlayerState(mVideoView.getCurrentPlayerState());
            if (mVideoView.isMute()) mVideoView.setMute(false);

            container.addView(mVideoView);

        }

        /**
         * 将播放器从父控件中移除
         */
        private void removePlayerFormParent(VideoView mVideoView) {
            if (mVideoView != null) {
                ViewParent parent = mVideoView.getParent();
                if (parent instanceof FrameLayout) {
                    ((FrameLayout) parent).removeView(mVideoView);
                }
            }

        }
    }


}
